package com.itzou.log;

import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.sql.*;
import java.text.SimpleDateFormat;

public class LogbackDbAppender extends AppenderBase<ILoggingEvent> {
    private String jdbcUrl;
    private String username;
    private String password;

    public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; }
    public void setUsername(String username) { this.username = username; }
    public void setPassword(String password) { this.password = password; }

    @Override
    protected void append(ILoggingEvent event) {
        try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password)) {
            String sql = "INSERT INTO sys_log (log_time, level, thread, logger, message) VALUES (?, ?, ?, ?, ?)";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setTimestamp(1, new Timestamp(event.getTimeStamp()));
                ps.setString(2, event.getLevel().toString());
                ps.setString(3, event.getThreadName());
                ps.setString(4, event.getLoggerName());
                ps.setString(5, event.getFormattedMessage());
                ps.executeUpdate();
            }
        } catch (Exception e) {
            // 这里不能再用 logger 打印，否则死循环
            e.printStackTrace();
        }
    }
}